/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.anjiplus.template.gaea.generator.api;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.anjiplus.template.gaea.generator.domain.Column;
import com.anjiplus.template.gaea.generator.domain.GenConfig;
import com.anjiplus.template.gaea.generator.service.GenConfigService;
import com.anjiplus.template.gaea.generator.service.GeneratorService;
import com.anjiplus.template.gaea.generator.utils.PageUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;

/**
 * @author Zheng Jie
 * @date 2019-01-02
 */
@RestController
@RequestMapping("/api/generator")
@Api(tags = "系统：代码生成管理")
@RefreshScope
public class GeneratorController {

    @Autowired(required = false)
    private GeneratorService generatorService;
    @Autowired(required = false)
    private GenConfigService genConfigService;

    @Value("${generator.enabled:false}")
    private Boolean generatorEnabled;

    @ApiOperation("查询数据库数据")
    @GetMapping(value = "/tables/all")
    public ResponseEntity<Object> queryTables(){
        return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK);
    }

    @ApiOperation("查询数据库数据")
    @GetMapping(value = "/tables")
    public ResponseEntity<Object> queryTables(
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "0")Integer page,
            @RequestParam(defaultValue = "10")Integer size){
        int[] startEnd = PageUtil.transToStartEnd(page, size);
        return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK);
    }

    @ApiOperation("查询字段数据")
    @GetMapping(value = "/columns")
    public ResponseEntity<Object> queryColumns(@RequestParam String tableName){
        List<Column> columnInfos = generatorService.getColumns(tableName);
        return new ResponseEntity(PageUtil.toPage(columnInfos,columnInfos.size()), HttpStatus.OK);
    }

    @ApiOperation("保存字段数据")
    @PostMapping(value = "/saveColumnCfg")
    public ResponseEntity<HttpStatus> save(@RequestBody List<Column> columnInfos){
        generatorService.saveColumnGenConfig(columnInfos);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("同步字段数据")
    @PostMapping(value = "sync")
    public ResponseEntity<HttpStatus> sync(@RequestBody List<String> tables){
        for (String table : tables) {
            generatorService.sync(generatorService.getColumns(table), generatorService.queryColumns(table));
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("生成代码")
    @PostMapping(value = "/{project}/{tableName}/{type}")
    public ResponseEntity<Object> generator(
            @PathVariable String project,
            @PathVariable String tableName,
            @PathVariable Integer type,
            HttpServletRequest request, HttpServletResponse response){
        if(!generatorEnabled && type == 0){
            throw new RuntimeException("此环境不允许生成代码，请选择预览或者下载查看！");
        }
        GenConfig config = genConfigService.find(project,tableName);

        switch (type){
            // 生成代码
            case 0:
                generatorService.generator(config, generatorService.getColumns(tableName));
                break;
            // 预览
            case 1: return generatorService.preview(config, generatorService.getColumns(tableName));
            // 打包
            case 2: generatorService.download(config, generatorService.getColumns(tableName),
                    request, response);
                    break;
            default: throw new RuntimeException("没有这个选项");
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
